package com.server.adapter;

import java.util.LinkedList;
import java.util.Queue;

import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.util.NodeList;

public class HTMLParser {
	/*
	 * define constants
	 */
	final int INDEX_START = 27;
	final int INTERVIEW_DATA_ENTRIES = 13;
	String[] interviewInfo = { "" };

	private String HTMLtext;
	public Queue<String> interviews_rawdata = new LinkedList<String>();

	/*
	 * constructor
	 */
	public HTMLParser(String HTMLtext) {
		this.HTMLtext = HTMLtext;
	}
	
	/*
	 * gets the html source from the Jobmine interview page
	 */
	public String[] getInterviews() {
		Parser parser;
		NodeList list = null;

		/*
		 *  sets filter to get the interview table
		 */
		HasAttributeFilter att_interviewTable = new HasAttributeFilter("id", "UW_CO_STUD_INTV$scroll$0");

		try {
			// if HTML text is null then return a null string[] for the interview data
			if (HTMLtext == null) {
				return null;
			} else {
				parser = new Parser(HTMLtext);
				list = parser.extractAllNodesThatMatch(att_interviewTable);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		/*
		 * removes the html tags
		 */
		String element = list.elementAt(0).toHtml().replaceAll("\\<.*?>", "");

		/*
		 * get each line of the html src
		 */
		String[] elements = element.split("\n");

		/*
		 * extract the useful interview data
		 */
		for (int i = INDEX_START; i < elements.length; i++) {
			if (!elements[i].equals(""))
				interviews_rawdata.add(elements[i]);
		}

		if (interviews_rawdata.size() == 0) {
			return interviewInfo;
		}

		interviewInfo = new String[(interviews_rawdata.size() + 1) / INTERVIEW_DATA_ENTRIES];
		String index;
		String jobID;
		String employerName;
		String jobTitle;
		String date;
		String type;
		String selectTime;
		String startTime;
		String length;
		String room;
		String instructions;
		String interviewer;
		String jobStatus;

		for (int i = 0; i < interviewInfo.length; i++) {
			index = interviews_rawdata.poll();
			jobID = interviews_rawdata.poll();
			employerName = interviews_rawdata.poll();
			jobTitle = interviews_rawdata.poll();
			date = interviews_rawdata.poll();
			type = interviews_rawdata.poll();
			selectTime = interviews_rawdata.poll();
			startTime = interviews_rawdata.poll();
			length = interviews_rawdata.poll();
			room = interviews_rawdata.poll();
			instructions = interviews_rawdata.poll();
			interviewer = interviews_rawdata.poll();
			jobStatus = interviews_rawdata.poll();

			interviewInfo[i] = index + "," + jobID + "," + employerName + "," + jobTitle + "," + date + "," + type + "," + selectTime + ","
					+ startTime + "," + length + "," + room + "," + interviewer + "," + jobStatus;
		}

		return interviewInfo;
	}
}